<?php
    /* Fingon 2011.07 */
    require_once('global.php');
    require_once('/code/Include/db_mysql.php');

    Class Category
    {
        private $db;

        public function Category(){
            $this->db=new DB();
        }

        public function getCategories($only_active=1, $sort='order by is_active DESC, sequence_num, name'){
            $sql='select *, (select count(*) from `product_category` where product_category.category_id=category.category_id) as item_count from `category`'.($only_active?' where `is_active`=1':'').' '.$sort;
            return $this->db->get_rows($sql); 
        }

        public function getCategory($cid){
            $sql='select *, (select count(*) from `product_category` where product_category.category_id=category.category_id) as item_count from `category` where `category_id` = '.$cid;
            return $this->db->get_one($sql);
        }
        
        public function getFirstCategoryId($sort='order by is_active DESC, sequence_num, name'){
            $sql='select category_id from `category`'.' '.$sort.' limit 0,1';
            $rs=$this->db->get_one($sql);
            return empty($rs['category_id']) ? 0 : $rs['category_id'];
        }

        public function editCategory($c){
            $c=$this->db->prepare_param($c);
            $sql=sprintf('update `category` set `name`=\'%s\', `descript`=\'%s\', `sequence_num`='.$c['sequence_num'].', `is_active`='.$c['is_active'].' where category_id='.$c['category_id'], $c['name'], $c['name']);
            $this->db->update($sql);
            return $this->db->affected_rows();
        }    
        
        public function addCategory($c){
            $c=$this->db->prepare_param($c);
            $sql=sprintf('insert into `category` (`name`, `descript`, `sequence_num`, `is_active`, `create_time`) values (\'%s\', \'%s\', '.$c['sequence_num'].', '.$c['is_active'].', now())', $c['name'], $c['name']);
            return $this->db->update($sql);
        } 
        
        public function deleteCategory($cid){
            if($this->categoryItemCount($cid)>0) return -1;
            $sql='delete from `category` where category_id='.$cid;
            $this->db->update($sql);
            return $this->db->affected_rows();
        }
        
        private function categoryItemCount($cid){
            $sql='select count(*) as item_count from product_category where category_id='.$cid;
            $rs=$this->db->get_one($sql);
            return intval($rs['item_count']);
        }
    }
?>